﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.Xml.Linq;

namespace PartyCraftServer.Web
{
    public abstract class WebHandler
    {
        public abstract void HandleRequest(HttpListenerContext Context);

        public static Dictionary<string, string> ParsePost(HttpListenerContext Context)
        {
            Dictionary<string, string> result = new Dictionary<string, string>();
            byte[] buffer = new byte[Context.Request.ContentLength64];
            Context.Request.InputStream.Read(buffer, 0, buffer.Length);
            string post = Context.Request.ContentEncoding.GetString(buffer);
            string[] parts = post.Split('&');
            foreach (string part in parts)
            {
                string[] values = part.Split('=');
                if (values.Length == 2)
                    result[values[0]] = values[1];
                else
                    result[part] = "";
            }
            return result;
        }

        protected void WriteResponse(HttpListenerContext Context, string value)
        {
            byte[] buffer = Encoding.UTF8.GetBytes(value);
            Context.Response.ContentLength64 = buffer.Length;
            Context.Response.OutputStream.Write(buffer, 0, buffer.Length);
        }

        protected void WriteXml(HttpListenerContext Context, XDocument xml)
        {
            WriteResponse(Context, "<?xml version=\"1.0\" ?>\n" + xml.ToString());
        }

        protected void Redirect(HttpListenerContext Context, string Url)
        {
            Context.Response.RedirectLocation = Url;
            Context.Response.StatusCode = 302;
            Context.Response.Close();
        }
    }
}
